<template>
  <div class="current-inventory">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>现有库存</span>
          <el-button type="primary" @click="refreshData">
            刷新数据
          </el-button>
        </div>
      </template>

      <!-- 搜索区域 -->
      <div class="search-area">
        <el-form :model="searchForm" inline>
          <el-form-item label="关键词">
            <el-input
              v-model="searchForm.keyword"
              placeholder="请输入商品名称、编号或型号"
              clearable
              style="width: 200px"
            />
          </el-form-item>
          <el-form-item label="库存状态">
            <el-select v-model="searchForm.stockStatus" placeholder="请选择库存状态" clearable style="width: 150px">
              <el-option label="正常库存" value="normal" />
              <el-option label="库存不足" value="low" />
              <el-option label="零库存" value="zero" />
            </el-select>
          </el-form-item>
          <el-form-item label="商品状态">
            <el-select v-model="searchForm.status" placeholder="请选择商品状态" clearable style="width: 120px">
              <el-option label="上架" :value="1" />
              <el-option label="下架" :value="0" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" :icon="Search" @click="handleSearch">
              搜索
            </el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 统计信息 -->
      <div class="stats-area">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-statistic title="商品总数" :value="stats.totalProducts" />
          </el-col>
          <el-col :span="6">
            <el-statistic title="上架商品" :value="stats.onlineProducts" />
          </el-col>
          <el-col :span="6">
            <el-statistic title="库存不足" :value="stats.lowStockProducts" />
          </el-col>
          <el-col :span="6">
            <el-statistic title="零库存" :value="stats.zeroStockProducts" />
          </el-col>
        </el-row>
      </div>

      <!-- 商品列表 -->
      <el-table
        :data="tableData"
        v-loading="loading"
        style="width: 100%"
        empty-text="暂无库存数据"
        :row-class-name="getRowClassName"
      >
        <el-table-column prop="productName" label="商品名称" min-width="120" />
        <el-table-column prop="productCode" label="商品编号" width="120" />
        <el-table-column prop="model" label="型号" width="100" />
        <el-table-column prop="supplyCost" label="供货成本" width="100">
          <template #default="scope">
            ¥{{ scope.row.supplyCost }}
          </template>
        </el-table-column>
        <el-table-column prop="sellingPrice" label="销售价格" width="100">
          <template #default="scope">
            ¥{{ scope.row.sellingPrice }}
          </template>
        </el-table-column>
        <el-table-column prop="currentStock" label="当前库存" width="100">
          <template #default="scope">
            <el-tag :type="getStockTagType(scope.row)">
              {{ scope.row.currentStock }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="minStock" label="最低库存" width="80">
          <template #default="scope">
            <span @click="showEditMinStockDialog(scope.row)" style="cursor: pointer; color: #409EFF;">
              {{ scope.row.minStock }}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="库存状态" width="100">
          <template #default="scope">
            <el-tag :type="getStockStatusTagType(scope.row)">
              {{ getStockStatusText(scope.row) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="商品状态" width="80">
          <template #default="scope">
            <el-tag :type="scope.row.status === 1 ? 'success' : 'danger'">
              {{ scope.row.status === 1 ? '上架' : '下架' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="supplierName" label="供应商" width="120" />
        <el-table-column prop="categoryName" label="分类" width="100" />
        <el-table-column prop="updateTime" label="最后更新" width="160">
          <template #default="scope">
            {{ formatTime(scope.row.updateTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="scope">
            <el-button
              type="primary"
              size="small"
              @click="showStockInDialog(scope.row)"
            >
              入库
            </el-button>
            <el-button
              type="info"
              size="small"
              @click="viewStockHistory(scope.row)"
            >
              记录
            </el-button>
            <el-button
              type="warning"
              size="small"
              @click="showEditMinStockDialog(scope.row)"
            >
              设置
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 入库对话框 -->
    <el-dialog
      v-model="stockInDialogVisible"
      title="商品入库"
      width="400px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="stockInFormRef"
        :model="stockInForm"
        :rules="stockInRules"
        label-width="100px"
      >
        <el-form-item label="商品名称">
          <el-input v-model="selectedProduct.productName" disabled />
        </el-form-item>
        <el-form-item label="当前库存">
          <el-input v-model="selectedProduct.currentStock" disabled />
        </el-form-item>
        <el-form-item label="最低库存">
          <el-input v-model="selectedProduct.minStock" disabled />
        </el-form-item>
        <el-form-item label="入库数量" prop="quantity">
          <el-input-number
            v-model="stockInForm.quantity"
            :min="1"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="stockInDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleStockIn" :loading="stockInSubmitting">
            确定入库
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 编辑最低库存对话框 -->
    <el-dialog
      v-model="editMinStockDialogVisible"
      title="设置最低库存"
      width="400px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="editMinStockFormRef"
        :model="editMinStockForm"
        :rules="editMinStockRules"
        label-width="100px"
      >
        <el-form-item label="商品名称">
          <el-input v-model="selectedProduct.productName" disabled />
        </el-form-item>
        <el-form-item label="当前库存">
          <el-input v-model="selectedProduct.currentStock" disabled />
        </el-form-item>
        <el-form-item label="当前最低库存">
          <el-input v-model="selectedProduct.minStock" disabled />
        </el-form-item>
        <el-form-item label="新最低库存" prop="minStock">
          <el-input-number
            v-model="editMinStockForm.minStock"
            :min="0"
            style="width: 100%"
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editMinStockDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleEditMinStock" :loading="editMinStockSubmitting">
            确定
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 库存记录对话框 -->
    <el-dialog
      v-model="stockHistoryDialogVisible"
      title="库存记录"
      width="800px"
    >
      <el-table
        :data="stockHistoryData"
        v-loading="stockHistoryLoading"
        style="width: 100%"
        empty-text="暂无记录"
      >
        <el-table-column prop="recordNo" label="记录编号" width="150" />
        <el-table-column prop="recordType" label="操作类型" width="80">
          <template #default="scope">
            <el-tag :type="scope.row.recordType === 'IN' ? 'success' : 'warning'">
              {{ scope.row.recordType === 'IN' ? '入库' : '出库' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="quantity" label="数量" width="80" />
        <el-table-column prop="beforeStock" label="操作前库存" width="100" />
        <el-table-column prop="afterStock" label="操作后库存" width="100" />
        <el-table-column prop="operatorName" label="操作员" width="100" />
        <el-table-column prop="remark" label="备注" min-width="120" />
        <el-table-column prop="createTime" label="操作时间" width="160">
          <template #default="scope">
            {{ formatTime(scope.row.createTime) }}
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import { getStoreProductPage, stockIn, updateStoreProductFields } from '@/api/storeProduct'
import { getStockRecordByProductId } from '@/api/stock'

// 响应式数据
const loading = ref(false)
const stockInSubmitting = ref(false)
const stockHistoryLoading = ref(false)
const editMinStockSubmitting = ref(false)
const tableData = ref([])
const stockHistoryData = ref([])
const stockInDialogVisible = ref(false)
const stockHistoryDialogVisible = ref(false)
const editMinStockDialogVisible = ref(false)
const stockInFormRef = ref()
const editMinStockFormRef = ref()

// 搜索表单
const searchForm = reactive({
  keyword: '',
  stockStatus: '',
  status: null
})

// 分页
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0
})

// 入库表单
const stockInForm = reactive({
  quantity: 1
})

// 编辑最低库存表单
const editMinStockForm = reactive({
  minStock: 0
})

// 选中的商品
const selectedProduct = ref({})

// 统计数据
const stats = reactive({
  totalProducts: 0,
  onlineProducts: 0,
  lowStockProducts: 0,
  zeroStockProducts: 0
})

// 表单验证规则
const stockInRules = {
  quantity: [
    { required: true, message: '请输入入库数量', trigger: 'blur' }
  ]
}

const editMinStockRules = {
  minStock: [
    { required: true, message: '请输入最低库存', trigger: 'blur' },
    { type: 'number', min: 0, message: '最低库存不能小于0', trigger: 'blur' }
  ]
}

// 格式化时间
const formatTime = (time) => {
  if (!time) return ''
  return new Date(time).toLocaleString()
}

// 获取库存标签类型
const getStockTagType = (row) => {
  if (row.currentStock === 0) return 'danger'
  if (row.currentStock <= row.minStock) return 'warning'
  return 'success'
}

// 获取库存状态标签类型
const getStockStatusTagType = (row) => {
  if (row.currentStock === 0) return 'danger'
  if (row.currentStock <= row.minStock) return 'warning'
  return 'success'
}

// 获取库存状态文本
const getStockStatusText = (row) => {
  if (row.currentStock === 0) return '零库存'
  if (row.currentStock <= row.minStock) return '库存不足'
  return '正常'
}

// 获取行样式类名
const getRowClassName = ({ row }) => {
  if (row.currentStock === 0) return 'zero-stock-row'
  if (row.currentStock <= row.minStock) return 'low-stock-row'
  return ''
}

// 获取表格数据
const getTableData = async () => {
  loading.value = true
  try {
    const params = {
      pageNum: pagination.current,
      pageSize: pagination.size,
      keyword: searchForm.keyword,
      status: searchForm.status
    }
    
    const response = await getStoreProductPage(params)
    if (response.code === 200) {
      let data = response.data.records || []
      
      // 根据库存状态过滤
      if (searchForm.stockStatus) {
        data = data.filter(item => {
          switch (searchForm.stockStatus) {
            case 'zero':
              return item.currentStock === 0
            case 'low':
              return item.currentStock > 0 && item.currentStock <= item.minStock
            case 'normal':
              return item.currentStock > item.minStock
            default:
              return true
          }
        })
      }
      
      tableData.value = data
      pagination.total = response.data.total || 0
      
      // 计算统计数据
      calculateStats(data)
    } else {
      ElMessage.error(response.message || '获取库存数据失败')
    }
  } catch (error) {
    console.error('获取库存数据失败:', error)
    ElMessage.error('获取库存数据失败')
  } finally {
    loading.value = false
  }
}

// 计算统计数据
const calculateStats = (data) => {
  stats.totalProducts = data.length
  stats.onlineProducts = data.filter(item => item.status === 1).length
  stats.lowStockProducts = data.filter(item => item.currentStock > 0 && item.currentStock <= item.minStock).length
  stats.zeroStockProducts = data.filter(item => item.currentStock === 0).length
}

// 搜索
const handleSearch = () => {
  pagination.current = 1
  getTableData()
}

// 重置搜索
const resetSearch = () => {
  searchForm.keyword = ''
  searchForm.stockStatus = ''
  searchForm.status = null
  pagination.current = 1
  getTableData()
}

// 刷新数据
const refreshData = () => {
  getTableData()
}

// 分页处理
const handleSizeChange = (val) => {
  pagination.size = val
  pagination.current = 1
  getTableData()
}

const handleCurrentChange = (val) => {
  pagination.current = val
  getTableData()
}

// 显示入库对话框
const showStockInDialog = (row) => {
  selectedProduct.value = { ...row }
  stockInForm.quantity = 1
  stockInDialogVisible.value = true
}

// 商品入库
const handleStockIn = async () => {
  if (!stockInFormRef.value) return
  
  try {
    await stockInFormRef.value.validate()
    stockInSubmitting.value = true
    
    const response = await stockIn(selectedProduct.value.id, stockInForm.quantity)
    if (response.code === 200) {
      ElMessage.success('入库成功')
      stockInDialogVisible.value = false
      getTableData()
    } else {
      ElMessage.error(response.message || '入库失败')
    }
  } catch (error) {
    console.error('入库失败:', error)
    ElMessage.error('入库失败')
  } finally {
    stockInSubmitting.value = false
  }
}

// 显示编辑最低库存对话框
const showEditMinStockDialog = (row) => {
  selectedProduct.value = { ...row }
  editMinStockForm.minStock = row.minStock
  editMinStockDialogVisible.value = true
}

// 编辑最低库存
const handleEditMinStock = async () => {
  if (!editMinStockFormRef.value) return

  try {
    await editMinStockFormRef.value.validate()
    editMinStockSubmitting.value = true

    const response = await updateStoreProductFields(selectedProduct.value.id, {
      minStock: editMinStockForm.minStock
    })

    if (response.code === 200) {
      ElMessage.success('最低库存设置成功')
      editMinStockDialogVisible.value = false
      getTableData()
    } else {
      ElMessage.error(response.message || '设置失败')
    }
  } catch (error) {
    console.error('设置最低库存失败:', error)
    ElMessage.error('设置失败')
  } finally {
    editMinStockSubmitting.value = false
  }
}

// 查看库存记录
const viewStockHistory = async (row) => {
  selectedProduct.value = { ...row }
  stockHistoryDialogVisible.value = true
  stockHistoryLoading.value = true

  try {
    // 使用供货商品ID查询库存记录，因为库存记录表中存储的是供货商品ID
    const productId = row.supplyProductId || row.id
    console.log('查询库存记录，店长商品ID:', row.id, '供货商品ID:', row.supplyProductId)
    const response = await getStockRecordByProductId(productId)
    if (response.code === 200) {
      stockHistoryData.value = response.data || []
      console.log('库存记录查询结果:', stockHistoryData.value)
    } else {
      ElMessage.error(response.message || '获取库存记录失败')
    }
  } catch (error) {
    console.error('获取库存记录失败:', error)
    ElMessage.error('获取库存记录失败')
  } finally {
    stockHistoryLoading.value = false
  }
}

// 初始化
onMounted(() => {
  getTableData()
})
</script>

<style scoped>
.current-inventory {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-area {
  margin-bottom: 20px;
}

.stats-area {
  margin-bottom: 20px;
  padding: 20px;
  background-color: #f5f7fa;
  border-radius: 4px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

/* 行样式 */
:deep(.zero-stock-row) {
  background-color: #fef0f0;
}

:deep(.low-stock-row) {
  background-color: #fdf6ec;
}
</style> 